/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package cn.clickmed.DaTong;

import java.lang.ref.WeakReference;

import org.apache.cordova.Config;
import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaWebView;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import cn.clickmed.certification.Cert;
import cn.com.jit.mctk.auth.exception.PNXAuthClientException;
import cn.com.jit.mctk.cert.exception.PNXCertException;
import cn.com.jit.mctk.common.exception.PNXClientException;
import cn.com.jit.mctk.net.exception.NetException;

import com.baidu.push.example.MyPushMessageReceiver;

public class DaTong extends CordovaActivity implements OnClickListener {

    public static DaTong dt = null;

    public static NotificationManager notificationManager = null;

    private static final int SHOW_TOAST_MSG = 1;

    private EditText credential;
    private String credStr;

    private String msg = "";
    protected DaTongHandler handler = new DaTongHandler(this);

    static class DaTongHandler extends Handler {
        WeakReference<DaTong> mActivity;

        DaTongHandler(DaTong activity) {
            mActivity = new WeakReference<DaTong>(activity);
        }

        @Override
        public void handleMessage(Message mesg) {
            DaTong theActivity = mActivity.get();
            switch (mesg.what) {
                case SHOW_TOAST_MSG:
                    Toast.makeText(theActivity, theActivity.msg, Toast.LENGTH_LONG)
                            .show();
                    break;
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        notificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        super.onCreate(savedInstanceState);
        DlgWait dlgWait = new DlgWait();
        dlgWait.ShowWait(this, "请等待...", "正在读取证书...", () -> {
            boolean isCertExisted = false;
            try {
                // Init once
                Cert.getInstance().setContext(DaTong.this);
                isCertExisted = Cert.getInstance().isCertExisted();
            } catch (PNXCertException e) {
                e.printStackTrace();
            }catch (PNXClientException e) {
                e.printStackTrace();
            }

            boolean finalIsCertExisted = isCertExisted;
            DaTong.this.runOnUiThread(() -> {
                //DaTong.this.loadUrl(Config.getStartUrl());
                //验证CA证书
                if (!finalIsCertExisted) {
                    initRegisterView();
                } else {
                    startCertValidation();  //验证证书
                }
            });
        });
        dt = this;
    }

    public static void closeSoftKeyboard(Context context, View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    // private void initLoginView() {
    // setContentView(R.layout.login_activity);
    // username = (EditText) findViewById(R.id.editText4);
    // password = (EditText) findViewById(R.id.editText5);
    // forgetPwd = findViewById(R.id.textView1);
    // changePwd = findViewById(R.id.textView2);
    // findViewById(R.id.button2).setOnClickListener(this);
    // forgetPwd.setOnClickListener(this);
    // changePwd.setOnClickListener(this);
    // }

    private void initRegisterView() {
        setContentView(R.layout.datong_register_activity);
        credential = (EditText) this.findViewById(R.id.editText1);
        this.findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.viewFocus1).requestFocus();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                closeSoftKeyboard(this, v);
                credStr = credential.getEditableText().toString().trim();
                if (isRegisterInputValid(credStr)) {
                    DlgWait dlgWait = new DlgWait();
                    dlgWait.ShowWait(this, "请等待...", "正在安装证书...", () -> {
                        boolean resultFlag = false;
                        try {
                            Cert.getInstance().setContext(DaTong.this);
                            //resultFlag = Cert.getInstance().requestCert(credStr, Configure.PASSWORD, Configure.GATEWAY_IP);
                            resultFlag = Cert.getInstance().requestCertWithPort(credStr, Configure.PASSWORD,Configure.GATEWAY_IP,Configure.GATEWAY_PORT_RZ);
                        } catch (PNXClientException e) {
                            e.printStackTrace();
                            msg = e.getErrorDesc();
                        } catch (PNXCertException e) {
                            e.printStackTrace();
                            msg = e.getErrorDesc();
                        } catch (NetException e) {
                            e.printStackTrace();
                            msg = e.getErrorMsg();
                        }

                        boolean finalResultFlag = resultFlag;
                        DaTong.this.runOnUiThread(() -> {
                            if (!finalResultFlag) {
                                msg = "证书安装失败，原因：" + msg;
                            } else {
                                msg = "证书安装成功！";
                            }
                            ToastHelper.getInstance().showToast(DaTong.this, msg);
                            if (finalResultFlag) {
                                String certSubject = "";
                                try {
                                    if (Cert.getInstance().getCertEntry() != null) {
                                        certSubject = Cert.getInstance().getCertEntry().getSubject();
                                    }
                                } catch (PNXCertException e) {
                                    e.printStackTrace();
                                }
                                DaTong.this.loadUrl(Config.getStartUrl() + "?host="
                                        + Cert.getInstance().getFinalUrl() + "&subject=" + certSubject);
                            }
                        });
                    });
                } else {
                    credential.requestFocus();
                }
                break;
            case R.id.textView1:
                break;
            case R.id.textView2:
                break;
            case R.id.button2:
                break;
        }

    }

    private void startCertValidation() {
        DlgWait dlgWait = new DlgWait();
        dlgWait.ShowWait(this, "请等待...", "正在验证身份...", () -> {
            boolean resultFlag = false;
            try {
                if (Cert.getInstance().getCertEntry() != null) {
                    resultFlag = Cert.getInstance().isAuthLoginSuccess(DaTong.this,
                            Configure.GATEWAY_IP, Cert.getInstance().getCertEntry().getAilas(),
                            Configure.PASSWORD);
                }
                if (!resultFlag) {
                    msg = "身份已失效！";
                }
                //resultFlag = Cert.getInstance().isAuthLoginSuccessWithPort(DaTong.this,
                // Configure.GATEWAY_IP,Configure.GATEWAY_PORT,Cert.getInstance().getCertEntry
                // ().getAilas(),Configure.PASSWORD);
            } catch (PNXAuthClientException e) {
                e.printStackTrace();
                msg = "身份验证失败！原因：" + e.getErrorDesc();
                handler.sendEmptyMessage(1);
                return;
            } catch (NetException e) {
                e.printStackTrace();
                msg = "身份验证失败！原因：" + e.getErrorMsg();
                handler.sendEmptyMessage(1);
                return;
            } catch (PNXCertException e) {
                e.printStackTrace();
                msg = "身份验证失败！原因：" + e.getErrorDesc();
                handler.sendEmptyMessage(1);
                return;
            }

            boolean finalResultFlag = resultFlag;
            DaTong.this.runOnUiThread(() -> {
                if(finalResultFlag){
                    DaTong.this.loadUrl(Config.getStartUrl());
                } else {
                    ToastHelper.getInstance().showToast(DaTong.this, msg);
                    DaTong.this.finish();
                }
            });

            /*20200916 chunzhao.li
            if (resultFlag) {
                try {
                    Cert.getInstance().initUrls(Configure.APP_ADDRESS,
                            Configure.APP_PORT);
                } catch (PNXAuthClientException e) {
                    e.printStackTrace();
                    msg = "获取应用代理地址失败！原因：" + e.getErrorDesc();
                    handler.sendEmptyMessage(1);
                    DaTong.this.finish();
                }
                if (Cert.getInstance().getFinalUrl() != null
                        && Cert.getInstance().getFinalUrl().length() > 0) {
                    msg = "身份验证成功，请登录";
                    handler.sendEmptyMessage(2);
                }
            } else {
                msg = "身份已失效！";
                handler.sendEmptyMessage(1);
                DaTong.this.finish();
            }*/
        });
    }

    private boolean isRegisterInputValid(String credStr) {
        if (credStr.length() == 0) {
            ToastHelper.getInstance().showToast(this,"请输入授权码");
            return false;
        }
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if ((intent.getExtras() != null)
                && (intent.getExtras().get("businessType") != null)) {
            setIntent(intent);
            String businessType = intent.getExtras().get("businessType")
                    .toString();
			MyPushMessageReceiver.messageMap.put(businessType, 0);
        }
        super.onNewIntent(intent);
    }

}
